<template>
  <div class="container order" v-loading="loading">
    <div class="handle-box">
      <el-input v-model="query.code" placeholder="兑换码" class="handle-input mr10"></el-input>
      <el-select v-model="query.status" placeholder="订单状态" style="width: 100px">
        <el-option
            v-for="item in orderStatus"
            :key="item.value"
            :label="item.label"
            :value="item.value"
        />
      </el-select>
      <el-button type="primary" :icon="Search" @click="fetchData">搜索</el-button>
      <el-button type="success" :icon="Plus" @click="addRedeem">添加兑换码</el-button>
      <el-button type="primary" :icon="Download" @click="exportRedeem">导出</el-button>
    </div>

    <el-row>
      <el-table :data="items" :row-key="row => row.id" table-layout="auto" @selection-change="handleSelectionChange">
        <el-table-column type="selection" :selectable="selectable" width="38"/>
        <el-table-column prop="name" label="名称" width="150"/>
        <!-- <el-table-column prop="code" label="兑换码"/> -->
        <el-table-column prop="code" label="兑换码" width="100">
          <template #default="scope">
            <el-text class="w-50px mb-2" truncated>
              {{ scope.row.code }}
            </el-text>
            <el-icon class="copy-model" :data-clipboard-text="scope.row.code">
              <DocumentCopy/>
            </el-icon>
          </template>
        </el-table-column>

        <el-table-column label="兑换人" width="90">
          <template #default="scope">
            <el-tag v-if="scope.row.username" type="success">{{ scope.row.username }}</el-tag>
            <el-tag v-else>未兑换</el-tag>
          </template>
        </el-table-column>

        <el-table-column prop="power" label="算力"/>

        <el-table-column label="生成时间" width="150">
          <template #default="scope">
            <span>{{ dateFormat(scope.row['created_at']) }}</span>
          </template>
        </el-table-column>

        <el-table-column label="兑换时间">
          <template #default="scope">
            <span v-if="scope.row['redeemed_at']">{{ dateFormat(scope.row['redeemed_at']) }}</span>
            <el-tag v-else>未兑换</el-tag>
          </template>
        </el-table-column>

        <el-table-column prop="enabled" label="启用状态" width="100">
          <template #default="scope">
            <el-switch v-model="scope.row['enabled']" @change="enable(scope.row)"/>
          </template>
        </el-table-column>

        <el-table-column label="操作" width="150">
          <template #default="scope">
            <el-popconfirm title="确定要删除当前记录吗?" @confirm="remove(scope.row)">
              <template #reference>
                <el-button size="small" type="danger">删除</el-button>
              </template>
            </el-popconfirm>
          </template>
        </el-table-column>

      </el-table>
    </el-row>

    <div class="pagination">
      <el-pagination v-if="total > 0" background
                     layout="total,prev, pager, next"
                     :hide-on-single-page="true"
                     v-model:current-page="page"
                     v-model:page-size="pageSize"
                     @current-change="fetchData()"
                     :total="total"/>

    </div>

    <el-dialog
        v-model="showDialog"
        :title="title"
        :close-on-click-modal="false"
    >
      <el-form :model="item" label-width="120px" ref="formRef" :rules="rules">
        <el-form-item label="名称：" prop="name">
          <el-input v-model="item.name" autocomplete="off" placeholder="请输入兑换码名称"/>
        </el-form-item>

        <el-form-item label="算力额度：" prop="power">
          <el-input v-model="item.power" autocomplete="off" placeholder="请输算力额度"/>
        </el-form-item>

        <el-form-item label="生成数量：" prop="quantity">
          <el-input v-model="item.quantity" autocomplete="off" placeholder="请输生成数量"/>
        </el-form-item>
      </el-form>

      <template #footer>
            <span class="dialog-footer">
              <el-button @click="showDialog = false">取消</el-button>
              <el-button type="primary" @click="save">提交</el-button>
            </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import {onMounted, onUnmounted, ref, reactive} from "vue";
import {httpGet, httpPost, httpPostExportRedeem} from "@/utils/http";
import {ElMessage} from "element-plus";
import {dateFormat, removeArrayItem} from "@/utils/libs";
import {Plus, Search, DocumentCopy, Download} from "@element-plus/icons-vue";

import ClipboardJS from "clipboard";
import FileSaver from 'file-saver';  // 使用FileSaver库来简化文件保存操作

// 变量定义
const items = ref([])
const item = ref({})
const showDialog = ref(false)
const title = ref("")
const query = ref({code: "", status: -1})
const total = ref(0)
const page = ref(1)
const pageSize = ref(15)
const loading = ref(true)
const formRef = ref(null)
const multipleSelection = ref([]);
const orderStatus = ref([
  {value: -1, label: "全部"},
  {value: 0, label: "未核销"},
  {value: 1, label: "已核销"},
])

const rules = reactive({
  name: [{required: true, message: '请输入兑换码名称', trigger: 'change',}],
  power: [{required: true, message: '请输算力额度', trigger: 'change',}],
  quantity: [{required: true, message: '请输生成数量', trigger: 'change',}],
})

const clipboard = ref(null)

onMounted(() => {
  fetchData()

  clipboard.value = new ClipboardJS('.copy-model');
  clipboard.value.on('success', () => {
    ElMessage.success('复制成功！');
  })

  clipboard.value.on('error', () => {
    ElMessage.error('复制失败！');
  })
})

onUnmounted(() => {
  clipboard.value.destroy()
})


// 获取数据
const fetchData = () => {
  query.value.page = page.value
  query.value.page_size = pageSize.value
  httpGet('/api/admin/redeem/list', query.value).then((res) => {
    if (res.data) {
      items.value = res.data.items
      total.value = res.data.total
      page.value = res.data.page
      pageSize.value = res.data.page_size
    }
    loading.value = false
  }).catch(e => {
    ElMessage.error("获取数据失败：" + e.message);
  })
}

// 判断是否已经被兑换了，兑换的 不能选中
const selectable = (row, index) => {
  if (typeof row.username === 'undefined' || row.username === null || row.username.trim().length === 0) {
    return true  //可勾选
  } else {
    return false  //不可勾选
  }
}


const handleSelectionChange = function (rows) {
  multipleSelection.value = rows.map(item => item.id);
  // multipleSelection.value = rows;
}


const exportRedeem = () => {

  // console.log('Selected rows:', multipleSelection.value);
  // 这里可以执行提交操作，例如发送请求到后端
  httpPostExportRedeem('/api/admin/redeem/export', multipleSelection.value).then((res) => {

    // 使用FileSaver库保存文件
    FileSaver.saveAs(new Blob([res.data], { type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' }), 'export-redeem.xlsx')

    ElMessage.success("操作成功！")

  }).catch(e => {
    ElMessage.error("操作失败：" + e.message)
  })
}


const addRedeem = function () {
  title.value = "生成兑换码"
  showDialog.value = true
  item.value = {
    "name": "100算力点卡",
    "power": 100,
    "quantity": 1
  }
}

const save = function () {
  formRef.value.validate((valid) => {
    if (valid) {
      showDialog.value = false
      item.value['power'] = parseFloat(item.value['power'])
      item.value['quantity'] = parseFloat(item.value['quantity'])

      httpPost('/api/admin/redeem/generate', item.value).then((res) => {
        ElMessage.success('操作成功！')
        fetchData()
      }).catch((e) => {
        ElMessage.error('操作失败，' + e.message)
      })

    } else {
      return false
    }
  })
}

const enable = (row) => {
  httpPost('/api/admin/redeem/enable', {id: row.id, enabled: row.enabled}).then(() => {
    ElMessage.success("操作成功！")
  }).catch(e => {
    ElMessage.error("操作失败：" + e.message)
  })
}

const remove = function (row) {
  httpGet('/api/admin/redeem/remove?id=' + row.id).then(() => {
    ElMessage.success("删除成功！")
    items.value = removeArrayItem(items.value, row, (v1, v2) => {
      return v1.id === v2.id
    })
  }).catch((e) => {
    ElMessage.error("删除失败：" + e.message)
  })
}

</script>

<style lang="stylus" scoped>
.order {

  .handle-box {
    margin-bottom 20px
    .handle-input {
      max-width 150px;
      margin-right 10px;
    }
  }

  .cell {
    .copy-model {
      margin-left 6px
      cursor pointer
    }
  }

  .opt-box {
    padding-bottom: 10px;
    display flex;
    justify-content flex-end

    .el-icon {
      margin-right: 5px;
    }
  }

  .el-select {
    width: 100%
    margin-right: 10px
  }

  .pagination {
    padding 20px 0
    display flex
    justify-content right
  }

}
</style>